/**
 * 
 */
package leetCode;


/**
 * @author zhongfang
 *
 */
public class TagValidator {
    public boolean isValid(String code) {
    	if(!(code.startsWith("<")&&code.endsWith(">"))){
    		return false;
    	}
    	int ind1=code.indexOf('>');
    	int ind2=code.lastIndexOf("</");//---------???
    	if(ind1==code.length()-1||ind2==-1){
    		return false;
    	}
    	
        String tagName1=code.substring(1, ind1);
    	String tagName2=code.substring(ind2+2,code.length()-1);
    	if(!tagName1.equals(tagName2)){
    		return false;
    	}
    	//检查tagName是否合法
    	boolean tagNameValid=validTagName(tagName1);
    	if(!tagNameValid){
    		return false;
    	}
    	String tagContent=code.substring(ind1+1,ind2);
    	boolean contentValid=validContent(tagContent);
    	if(!contentValid){
    		return false;
    	}
    	return true;
    }
	private boolean validContent(String tagContent) {
		int start=tagContent.indexOf('<');
		int end=tagContent.lastIndexOf('>');//这里不准确，因为最后可以随便有>
		if(start!=-1&&end<start){//没有匹配的>
			return false;
		}
		if(start!=-1&&end!=-1){
			int startRight=tagContent.indexOf('>',start+1);//在<之后的>
			String tagName=tagContent.substring(start+1,startRight);
			int endTagName=tagContent.lastIndexOf("</"+tagName+">");
			int newEnd=endTagName+3+tagName.length();
			boolean isValidClosedTag=endTagName!=-1&&isValid(tagContent.substring(start,newEnd));
			if(isValidClosedTag){
					return validContent(tagContent.substring(newEnd));
			}
			
			String target=tagContent.substring(start);
			int endCDATA=target.indexOf("]]>");
			boolean isValidCDATA=endCDATA!=-1&&target.startsWith("<![CDATA[");
			if(isValidCDATA){
				return validContent(target.substring(endCDATA+3));
			}
			
			return false;//< 不能匹配closedTag 和CDATA
		}
		
		return true;//没有<
	}
	private boolean validTagName(String tagName1) {
		int len=tagName1.length();
		if(len==0||len>9){
			return false;
		}
		for (int i = 0; i < len; i++) {
			char ch=tagName1.charAt(i);
			if(ch<'A'||ch>'Z'){
				return false;
			}
		}
		return true;
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		TagValidator tagValidator=new TagValidator();
		String[] strings={"<A><A>456</A>  <A> 123  !!  <![CDATA[]]>  123 </A>   <A>123</A></A>"
,"<A><A>/A></A></A>","<DIV>This is the first line <![CDATA[<div>]]></DIV>","<DIV>>>  ![cdata[]] <![CDATA[<div>]>]]>]]>>]</DIV>","<DIV>  div tag is not closed  <DIV>","<A>  <B> </A>   </B>","<DIV>  unmatched <  </DIV>","<DIV> closed tags with invalid tag name  <b>123</b> </DIV>","<DIV> unmatched tags with invalid tag name  </1234567890> and <CDATA[[]]>  </DIV>","<DIV>  unmatched start tag <B>  and unmatched end tag </C>  </DIV>"};
		for (String string : strings) {
			System.out.println(tagValidator.isValid(string));
		}
	}

}
